package com.ruoyi.wechat.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wechat.domain.BusinessWechat;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 彩虹屁接口调用
 *
 * @author xied
 */
public class RainbowUtil {
    public static AjaxResult getRainbow(BusinessWechat businessWechat) {
        String httpUrl = "http://api.tianapi.com/caihongpi/index?key=" + businessWechat.getTianapiAk();
        BufferedReader reader = null;
        String rs = null;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                stringBuilder.append(strRead);
                stringBuilder.append("\r\n");
            }
            reader.close();
            rs = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONUtil.parseObj(rs);

        // 获取接口响应状态
        String code = String.valueOf((Integer) jsonObject.get("code"));
        if (!"200".equals(code)) {
            // 如果响应状态不为200,则调用出错
            String msg = (String) jsonObject.get("msg");
            return AjaxResult.error(code, "天行数据接口调用报错:" + msg);
        }
        JSONArray newslist = jsonObject.getJSONArray("newslist");
        String data = "\n" + newslist.getJSONObject(0).get("content");
        return AjaxResult.success(code, data);
    }

}
